package com.gzu;

import java.sql.*;
import java.time.LocalDate;

public class TeacherBatchInsert {
    public static void batchInsertTeachers(Connection conn) {
        // 检查数据库中已有的记录数
        int existingCount = countExistingTeachers(conn);
        int startId = existingCount + 1; // 从已有记录的下一个ID开始插入

        String sql = "INSERT INTO teacher (id, name, course, birthday) VALUES (?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            for (int i = startId; i <= 500; i++) {
                pstmt.setInt(1, i);
                pstmt.setString(2, "Teacher" + i);
                pstmt.setString(3, "Course" + i);
                pstmt.setDate(4, Date.valueOf(LocalDate.now().minusDays(365 * 30))); // Assuming 30 years old
                pstmt.addBatch();
                if ((i - startId + 1) % 100 == 0 || i == 500) {
                    pstmt.executeBatch();
                    conn.commit();
                }
            }
        } catch (SQLException e) {
            try {
                conn.rollback(); // 发生异常时回滚事务
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    private static int countExistingTeachers(Connection conn) {
        String countSql = "SELECT COUNT(*) FROM teacher";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(countSql)) {
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0; // 如果发生异常，返回0
    }
}